package com.shixi.controller;

import com.shixi.domain.User;
import com.shixi.service.AdminService;
import com.shixi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    AdminService adminService;

    @Autowired
    UserService userService;

    /*访问登录页面*/
    @RequestMapping("/toLogin")
    public String toLogin()
    {
        return "login";
    }


    /*验证登录*/
    @RequestMapping("/login")
    public String login(String username, String password, String adminType, Model model, HttpServletRequest request)
    {
        /*调用验证登录的逻辑类去验证登录*/
        if(adminType.equals("1")){
            if(adminService.checkLogin(username,password,request)==true)
            {
                return "index";
            }else {
                model.addAttribute("msg","用户名或者密码错误！");
                return "login";
            }
        }else if(adminType.equals("2")){
            if(userService.checkLogin(username,password,request)==true)
            {
                return "userindex";
            }else {
                model.addAttribute("msg","用户名或者密码错误！");
                return "login";
            }
        }else {
                model.addAttribute("msg","用户类型错误！");
                return "login";
        }

    }

    /*修改密码*/
    @RequestMapping("/updatePassword")
    public String toupdatePassword(){
        return "update/updatePwd";
    }

    /*修改用户密码*/
    @RequestMapping("/updatePwdSubmit")
    @ResponseBody
    public Map<String,Object> updatePwd(String oldPwd, String newPwd, HttpServletRequest request)
    {
        System.out.println("进入修改密码的控制器！");

        User user = (User) request.getSession().getAttribute("loginUser");
        String username = user.getUsername();

        /*调用UserService内的修改密码的业务*/
        boolean updateresult = userService.updatePwd(username,oldPwd,newPwd,request);
        HashMap<String,Object> map = new HashMap<>();
        if(updateresult==true)
        {
            map.put("code",0);
        }
        else {
            map.put("code",-1);
        }
        return map;
    }

}
